const request = require('../../utils/request');

Page({
  data: {
    phone: '',
    smsCode: '',
    password: '',
    confirmPassword: '',
    countdown: 0
  },

  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },

  onSmsCodeInput(e) {
    this.setData({ smsCode: e.detail.value });
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },

  onConfirmPasswordInput(e) {
    this.setData({ confirmPassword: e.detail.value });
  },

  getSmsCode() {
    const phone = this.data.phone;
    console.log('🚀 注册页面 - 点击获取验证码，手机号:', phone);

    if (!phone) {
      wx.showToast({ title: '请输入手机号', icon: 'none' });
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({ title: '请输入正确手机号', icon: 'none' });
      return;
    }

    console.log('⏰ 开始倒计时');
    this.setData({ countdown: 60 });
    const timer = setInterval(() => {
      this.setData({ countdown: this.data.countdown - 1 });
      if (this.data.countdown === 0) {
        clearInterval(timer);
        console.log('⏰ 倒计时结束');
      }
    }, 1000);

    console.log('📡 发送请求到:', request.buildUrl ? request.buildUrl('/api/auth/send-sms') : '/api/auth/send-sms');
    request({
      url: '/api/auth/send-sms',
      method: 'POST',
      data: { phone }
    }).then((res) => {
      console.log('✅ 请求成功，响应数据:', res);
      if (res.success) {
        wx.showToast({ title: '验证码已发送' });
        if (res.data && res.data.smsCode) {
          console.log('🔢 测试验证码:', res.data.smsCode);
        }
      } else {
        wx.showToast({ title: res.message || '发送失败', icon: 'none' });
      }
    }).catch((err) => {
      console.error('❌ 请求失败:', err);
      wx.showToast({ title: '网络错误，请检查服务器', icon: 'none' });
    });
  },

  register() {
    const { phone, smsCode, password, confirmPassword } = this.data;

    if (!phone || !smsCode || !password || !confirmPassword) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }

    if (password !== confirmPassword) {
      wx.showToast({ title: '两次密码不一致', icon: 'none' });
      return;
    }

    if (password.length < 8) {
      wx.showToast({ title: '密码至少8位', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '注册中...' });
    request({
      url: '/api/auth/register-with-sms',
      method: 'POST',
      data: { phone, smsCode, password }
    }).then((res) => {
      wx.hideLoading();
      if (res.success) {
        wx.showToast({ title: '注册成功' });
        setTimeout(() => {
          wx.reLaunch({ url: '/pages/login/login' });
        }, 1500);
      } else {
        wx.showToast({ title: res.message || '注册失败', icon: 'none' });
      }
    }).catch(() => {
      wx.hideLoading();
      wx.showToast({ title: '网络错误', icon: 'none' });
    });
  },

  goToLogin() {
    wx.navigateBack();
  }
});